package com.kit.web.controller.adv;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kit.advert.domain.AdvertTimes;
import com.kit.advert.service.IAdvertTimesService;
import com.kit.common.core.controller.BaseController;
import com.kit.common.core.domain.AjaxResult;
import com.kit.common.core.page.TableDataInfo;
import com.kit.common.utils.PageUtils;
import com.kit.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.text.SimpleDateFormat;
import java.util.Objects;


@RestController
@RequestMapping("/advert/times")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AdvertTimesController extends BaseController {

    private final IAdvertTimesService advertTimesService;

    /**
     * 新增时段
     * @param times
     * @return
     */
    @PostMapping("/saveTimes")
    public AjaxResult saveTime(@RequestBody @Validated AdvertTimes times){
        return toAjax(advertTimesService.save(times));
    }

    /**
     * 时段时段
     * @param times
     * @return
     */
    @PostMapping("/editTime")
    public AjaxResult editTime(@RequestBody @Validated AdvertTimes times){
        AdvertTimes advertTimes = advertTimesService.getById(times.getTimeId());
        if (Objects.isNull(advertTimes)) {
            return AjaxResult.error("需要修改的广告时段不存在");
        }
        return toAjax(advertTimesService.save(times));
    }

    /**
     * 分页查询
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return  返回查询结果
     */
    @GetMapping("/page")
    public TableDataInfo<AdvertTimes> page(@PathParam("startTime") String startTime, @PathParam("endTime") String endTime){
        // 格式验证
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        QueryWrapper<AdvertTimes> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(startTime)) {
            try {
                sdf.parse(startTime);
            } catch (Exception e) {
                logger.error("开始时间格式错误");
            }
            queryWrapper.le("end_time", startTime);
        }
        if (StringUtils.isNotBlank(endTime)) {

            try {
                sdf.parse(endTime);
            } catch (Exception e) {
                logger.error("结束时间格式错误");
            }
            queryWrapper.le("start_time", endTime);
        }
        Page<AdvertTimes> page = advertTimesService.page(PageUtils.buildPage(), queryWrapper);
        return PageUtils.buildDataInfo(page);
    }
}
